$(function () {
  initEditor();
  const form = layui.form;
  let state = '已发布';
  // 1. 初始化图片裁剪器
  let $image = $('#image');

  // 2. 裁剪选项
  let options = {
    aspectRatio: 400 / 280,
    preview: '.img-preview'
  };

  // 3. 初始化裁剪区域
  $image.cropper(options);

  $.ajax({
    url: '/my/article/cates',
    method: 'GET',
    success: (res) => {
      if (res.status !== 0) {
        return layer.msg(res.message);
      }

      let htmlTpl = res.data
        .map((item) => {
          return `<option value="${item.Id}">${item.name}</option>`;
        })
        .join('');
      $('[name=cate_id]').html(htmlTpl);

      form.render();
    }
  });

  $('#upload_avatar').click(function () {
    $('#file').click();
  });

  //监听input框的选择
  $('#file').change((e) => {
    let fileList = e.target.files;
    console.log(fileList);
    let imgUrl = URL.createObjectURL(fileList[0]);
    console.log(imgUrl);

    //重新初始化裁切区域
    $image.cropper('destroy').attr('src', imgUrl).cropper(options);

    //更新头像
    $('#update_avatar').click(function () {
      let dataURL = $image
        .cropper('getCroppedCanvas', {
          // 创建一个 Canvas 画布
          width: 100,
          height: 100
        })
        .toDataURL('image/png');

      $.ajax({
        method: 'POST',
        url: '/my/update/avatar',
        data: {
          avatar: dataURL
        },
        success: function (res) {
          if (res.status !== 0) {
            return layer.msg('更换头像失败！');
          }
          layer.msg('更换头像成功！');
          window.parent.getUserInfo();
        }
      });
    });
  });

  $('#pub_form').on('submit', (e) => {
    e.preventDefault();
    let fd = new FormData($('#pub_form')[0]);
    fd.append('state', state);
    $image
      .cropper('getCroppedCanvas', {
        width: 100,
        height: 100
      })
      .toBlob((blob) => {
        console.log(blob);
        fd.append('cover_img', blob);

        $.ajax({
          url: '/my/article/add',
          method: 'POST',
          contentType: false,
          processData: false,
          data: fd,
          success: (res) => {
            console.log(res);
            if (res.state !== 0) {
              return layer.msg(res.message);
            }
            layer.msg('发布成功');
            location.href = '/article/art_list.html';
          }
        });
      });
  });

  $('save_btn').on('click', function () {
    state = '草稿';
  });
});
